package com.supermap.wzhy.module.user.api;

import com.supermap.wzhy.common.annotation.Permission;
import com.supermap.wzhy.common.annotation.Role;
import com.supermap.wzhy.common.api.BaseController;
import com.supermap.wzhy.data.OpStatus;
import com.supermap.wzhy.data.PageInfo;
import com.supermap.wzhy.data.UserInfo;
import com.supermap.wzhy.data.cons.UserType;
import com.supermap.wzhy.entity.TUsermajor;
import com.supermap.wzhy.entity.TUserpowercatalog;
import com.supermap.wzhy.entity.TUserrole;
import com.supermap.wzhy.entity.TUsers;
import com.supermap.wzhy.module.sys.service.RegionInfoService;
import com.supermap.wzhy.module.user.service.UserLoginService;
import com.supermap.wzhy.module.user.service.UserMajorService;
import com.supermap.wzhy.module.user.service.UserRoleService;
import com.supermap.wzhy.module.user.service.UserService;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by W.Hao on 14-1-21.
 * 用户信息
 */
@Controller
@RequestMapping(value = {"/users","/service/users"})
public class UserController extends BaseController {

    @Autowired
    UserLoginService userLoginService;
    @Autowired
    UserService userService;
    @Autowired
    UserRoleService userRoleService;
    @Autowired
    UserMajorService userMajorService;
    /** 行政区划信息server */
    @Autowired
    private RegionInfoService regionInfoService;

    /**
     * 用户列表
     * @param key
     * @param pageInfo
     * @return
     */
    @RequestMapping(value = "/all", method = RequestMethod.POST)
    @ResponseBody
    public List<TUsers> getAll(HttpServletRequest request,String key, @RequestBody PageInfo pageInfo){
        String sql = null;
        if(key!=null && key!=""){
            sql = "SELECT t FROM TUsers t WHERE 1=1 " + key + " order by t.userid";
        }else{
            sql = "SELECT t FROM TUsers t order by t.userid";
        }
        List<TUsers> userList = this.userService.getAll(sql,pageInfo);
        return userList;
    }

    @RequestMapping(value = "/size", method = RequestMethod.POST)
    @ResponseBody
    public int size(HttpServletRequest request,String key){
        String sql = null;
        if(key!=null && key!=""){
            sql = "FROM T_USERS t WHERE " + key;
        }else{
            sql = "FROM T_USERS t";
        }
        int size = this.userService.size(sql);
        return size;
    }

    /**
     * 创建用户
     *
     * @param user
     *          若roleid存在，则添加用户的角色
     * @return
     */
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    @ResponseBody
    public OpStatus createUser(@RequestBody TUsers user){
        boolean re=false;
        if (userService.checkUserNameExists(user.getUserName())){
            return new OpStatus(re,"用户名已存在，添加失败！",null);
        }
        re =userService.create(user);

        return new OpStatus(re,re ? "添加成功！":"添加失败！",null);
    }

    @Permission(Role.ADMIN)
    @RequestMapping(value = "/batch", method = RequestMethod.POST)
    public @ResponseBody OpStatus batchUsers(int catalog,int level,String password,int sys_role,int roleid){
        int re = userService.createByLevel(catalog,level,password,sys_role,roleid);
        return  new OpStatus(re>0,"成功创建"+re+"个用户",null);
    }


    @Permission(Role.USER)
    @RequestMapping(value = "", method = RequestMethod.GET)
    public @ResponseBody List<UserInfo> getAllUser() {
        return userService.query();
    }

    @Permission(Role.USER)
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public  @ResponseBody TUsers getUser(@PathVariable("id") int id){
        return  userService.one(id);
    }

    @RequestMapping(value = "/get", method = RequestMethod.POST)
    @ResponseBody
    public TUsers getUserInfos(@RequestBody String id){
        return  userService.getUserInfos(Integer.parseInt(id));
    }

    /**
     * 删除用户
     * @param ids
     * @return
     */
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    @ResponseBody
    public OpStatus deleteUser  (@RequestBody String[] ids) {
        List<Integer> idList = new ArrayList<>();
        for(String id:ids){
            int intId = Integer.parseInt(id);
            TUsers user = userService.getUserInfos(intId);
            if(user.getUserName().equals("admin")){
                return new OpStatus(false,"不能删除管理员",null);
            }else{
                int re = userService.delete(id);
                idList.add(re);
                if(re<=0){
                    return new OpStatus(false,"删除失败",null);
                }
            }
        }
        if(idList.size() > 0){
            return  new OpStatus(true,"成功删除"+idList.size()+"个用户",null);
        }
        return new OpStatus(true,"",null);
    }

    /**
     * 修改用户信息
     * @param user
     * @return
     */
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    @ResponseBody
    public OpStatus updateUser(@RequestBody TUsers user) {
        String sql = "FROM T_USERS t WHERE t.USER_NAME='" + user.getUserName() + "' AND t.USERID <> " + user.getUserid();
        int size = this.userService.size(sql);
        if (size > 0){
            return new OpStatus(false,"用户名已存在，修改失败！",null);
        }
        boolean re = userService.update( user);
        return getOpStatus(re);

    }

    /**
     * 取得指定用户的角色
     * @param response
     * @param id
     * @return
     */
    @RequestMapping(value="/{id}/roles", method=RequestMethod.GET)
    public @ResponseBody List<TUserrole> getUserRoles(HttpServletResponse response,@PathVariable("id") int id) {
        return userRoleService.getByUserid(id);

    }

    /**
     * 设置指定用户的角色
     * @param response
     * @param userid
     *          指定用户
     * @param roleids
     *          需要设置的权限
     * @return
     */
    @RequestMapping(value="/{id}/setroles", method=RequestMethod.POST)
    public @ResponseBody OpStatus setUserRoles(HttpServletResponse response
            ,@PathVariable("id") int userid,String roleids) {
        int count =  userService.setUserRolesByUserid(userid,roleids);
        return new OpStatus(count>0,"设置"+count+"个角色",null);
    }

    @RequestMapping(value="/{id}/powerCatalogs", method=RequestMethod.GET)
    public @ResponseBody List<TUserpowercatalog> getUserPowerCatalogs(@PathVariable("id") int id) {
        return null;

    }
    @RequestMapping(value="/{id}/majors", method=RequestMethod.GET)
    public @ResponseBody List<TUsermajor> getUserMajors(@PathVariable("id") int id) {
        return userMajorService.getByUserid(id);

    }
/*
    @RequestMapping(value="/{id}/logs", method=RequestMethod.GET)
     public @ResponseBody List<TLog> getUserLogs(@PathVariable("id") int id) {
        return userLogService.getByUserid(id);

    }
*/

    /**
     * 下载导入用户的模板
     *
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping(value = "import/template/download",method = RequestMethod.GET)
    @ResponseBody
    public void downloadTempalte(HttpServletRequest request,HttpServletResponse response)
            throws  Exception{
        String filename = new String("用户导入模板(操作员类型用户)".getBytes(),"iso8859-1");
        response.reset();
        response.setContentType("APPLICATION/vnd.ms-excel");
        //注意，如果去掉下面一行代码中的attachment; 那么也会使IE自动打开文件。
        response.setHeader("Content-Disposition", "attachment;filename="+filename+".xls");
        HSSFWorkbook wk = userService.downloadTemplate();
        OutputStream out  =response.getOutputStream() ;
        wk.write(out);
        out.flush();
        out.close();
    }

    /**
     *  导入用户操作
     * @param request
     * @param path
     * @param sheetName
     * @param roleid
     * @return
     */
    @RequestMapping(value="/import")
    @ResponseBody
    public OpStatus importUsers(HttpServletRequest request,@Param("path") String path
            ,@Param("sheetName") String sheetName,@Param("roleid") int roleid) {
        Map<String,Object> re= userService.importUser(path,sheetName,1,roleid);//从序号1行读

        return new OpStatus((boolean)re.get("status"),re.get("msg").toString(),null);
    }

    @RequestMapping(value = "/login",method = {RequestMethod.POST,RequestMethod.GET})
    @ResponseBody
    public  TUsers Login(HttpServletRequest request,String userName,String password){
        TUsers tUsers = userLoginService.checkUser(userName,password);
        this.setSessionUser(request,tUsers);
        return  tUsers;
    }
//        @RequestMapping(value="/test",method=RequestMethod.GET,produces = "plain/text; charset=UTF-8")
    @RequestMapping(value="/test",method=RequestMethod.GET)
    public @ResponseBody OpStatus test(@RequestParam String param){
        System.out.println(param);
        return  new OpStatus();
    }

    /**
     * 获取所有的用户类型(一共有五种类型：1~5)
     *
     * @return
     */
    @RequestMapping(value = "/allsysrole",method = {RequestMethod.POST,RequestMethod.GET})
    public @ResponseBody List getAllSysRole(){
        return UserType.getAllType();
    }


    /**
     * 修改密码
     * @param userName
     * @param password
     * @return
     */
    @RequestMapping(value = "/edit/sim",method = RequestMethod.GET)
    @ResponseBody
    public OpStatus editUserInfo(String userName,String password,HttpServletRequest request){
        TUsers sessionUser = getSessionUser(request);
        if(sessionUser!=null){
            if(userName!=null && !userName.trim().isEmpty()){
                sessionUser.setUserName(userName);
            }
            if(password!=null && !password.trim().isEmpty()){
                sessionUser.setPassword(password);
            }
            boolean bl = userService.simpleUpdate(sessionUser);
            if(bl){
                return new OpStatus(true,"修改成功，请重新登陆",null);
            }else{
                return new OpStatus(false,"",null);
            }
        }
        return new OpStatus(false,"请登录",null);
    }

    /**
     * 修改密码
     * @param id
     * @param password
     * @return
     */
    @RequestMapping(value = "/rePassword",method = RequestMethod.POST)
    @ResponseBody
    public OpStatus modifyPassword(int id,String password){
        boolean re = this.userService.rePassword(id,password);
        return new OpStatus(re,re?"修改成功！":"修改失败！",null);
    }

}
